<template>
  <el-row>
    <el-col :span="8">
      <el-form-item label="妊检日期">
        <el-date-picker
          v-model="form.DateTime"
          type="datetimerange"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          format="YYYY-MM-DD  " /></el-form-item
    ></el-col>

    <el-col style="margin-left: 20px" :span="4"
      ><el-form-item label="种母耳号">
        <el-select
          style="width: 200px"
          clearable
          v-model="form.earNo"
          placeholder="请选择"
        >
          <el-option
            v-for="item in sleepInfoDatas"
            :label="item.earNumber"
            :value="item.sleepInforId"
          /> </el-select></el-form-item
    ></el-col>
    <el-col :span="8">
      <el-form-item label="负责人">
        <el-select
          v-model="form.leader"
          placeholder="请选择"
          style="width: 240px"
        >
          <el-option label="罗翔" value="罗翔" />
          <el-option label="扬家霖" value="扬家霖" />
          <el-option label="雷鑫" value="雷鑫" />
          <el-option label="王单青" value="王单青" />
          <el-option label="温暖暖" value="温暖暖" />
          <el-option label="杨杰" value="杨杰" />
          <el-option label="赵丽" value="赵丽" />
          <el-option label="黄强" value="黄强" />
          <el-option label="吴敏" value="吴敏" />
          <el-option label="周亮" value="周亮" />
          <el-option label="徐蕾" value="徐蕾" />
          <el-option label="孙伟" value="孙伟" />
          <el-option label="李霞" value="李霞" />
          <el-option label="马超" value="马超" />
          <el-option label="郭丽" value="郭丽" />
          <el-option label="高峰" value="高峰" />
          <el-option label="何敏" value="何敏" />
          <el-option label="林静" value="林静" />
          <el-option label="罗文" value="罗文" />
          <el-option label="蒋娜" value="蒋娜" /> </el-select></el-form-item
    ></el-col>
  </el-row>

  <el-row>
    <el-col :span="6"
      ><el-form-item label="妊检结果:" style="width: 170px">
        <el-select v-model="form.pregnancyTestResult" placeholder="请选择">
          <el-option
            v-for="item in pregntest"
            :label="item.pregnancyTestResultName"
            :value="item.pregnancyTestResult"
          />
        </el-select> </el-form-item
    ></el-col>
    <el-col :span="12"
      ><el-form-item label="同胎数">
        <el-input
          v-model="form.litterCount"
          placeholder="请输入"
          style="width: 70px"
        /> </el-form-item
    ></el-col>
  </el-row>
  <el-button :icon="Search" type="primary" @click="getDatas()">查询</el-button>
  <el-button
    :icon="Plus"
    type="success"
    @click="router.push('Month_breddingAdd')"
    >新增</el-button
  >
  <el-button :icon="Delete" type="danger">删除</el-button>
  <el-button type="danger">审核</el-button>
  <h2 style="background-color: lightpink; margin-top: 20px" v-if="totals != 0">
    &emsp;&emsp;已选择 {{ totals }} 条
  </h2>
  <el-table
    :data="tableData"
    border
    style="max-width: 100%"
    @selection-change="handleSelectionChange"
    :header-cell-style="{
      height: '100px',
      fontSize: '15px',
      color: 'black',
      backgroundColor: 'antiquewhite',
    }"
  >
    <el-table-column type="selection" />
    <el-table-column prop="ewePregnancyCheckRecordId" label="序号" >
      <template #default="{$index}">
                  {{ $index+1 }}
      </template>
    </el-table-column>
    <el-table-column prop="pregnancyTestDate" label="妊检日期">
      <template v-slot="scope">
        {{ scope.row.pregnancyTestDate.substring(0, 19).replace('T', ' ') }}
      </template>
    </el-table-column>

    <el-table-column prop="earNumber" label="耳号" />
    <el-table-column prop="pregnancyTestResultName" label="妊检结果" />
    <el-table-column prop="pregnancyCheckMethodName" label="妊检方式" />
    <el-table-column prop="litterCount" label="同胎数" />
    <el-table-column prop="pregnancyDays" label="妊振天数">
      <template #default="scope"> {{ scope.row.pregnancyDays }}天 </template>
    </el-table-column>
    <el-table-column prop="currentBarn" label="当前栋舍" />
    <el-table-column prop="currentPen" label="当前栏位" />
    <el-table-column prop="transferBarn" label="转入栋舍" />
    <el-table-column prop="transferPen" label="转入栏位" />
    <el-table-column prop="leader" label="负责人" />
    <el-table-column prop="createId" label="创建人" >
       <template #default="scope">
          <span v-if="scope.row.createId==1">罗Sir</span>
       </template>
    </el-table-column>
    <el-table-column prop="createTime" label="创建时间">
      <template v-slot="scope">
        {{ scope.row.createTime.substring(0, 19).replace('T', ' ') }}
      </template>
    </el-table-column>
    <el-table-column prop="updateId" label="修改人" />
    <el-table-column prop="updateTime" label="修改时间">
      <template v-slot="scope">
        {{
          scope.row.updateTime == null
            ? ''
            : scope.row.updateTime.substring(0, 19).replace('T', ' ')
        }}
      </template>
    </el-table-column>
    <el-table-column prop="examId" label="审核人" />
    <el-table-column prop="examTime" label="审核时间">
      <template v-slot="scope">
        {{
          scope.row.examTime == null
            ? ''
            : scope.row.examTime.substring(0, 19).replace('T', ' ')
        }}
      </template>
    </el-table-column>
    <el-table-column prop="documentNo" label="单据号" />
    <el-table-column label="操作">
      <template #default="scope">
        <el-button
          type="danger"
          :icon="Delete"
          circle
          @click="handleDelete(scope.row.ewePregnancyCheckRecordId)"
        ></el-button>
        <!-- <el-button type="primary" @click="handleUpdate(scope.row)"
          >修改</el-button
        > -->
        <el-button
          type="primary"
          :icon="Edit"
          circle
          @click="detailCottage(scope.row)"
        />
      </template>
    </el-table-column>
  </el-table>

  <el-pagination
    v-model:current-page="page.pageIndex"
    v-model:page-size="page.pageSize"
    :page-sizes="[5, 10, 15, 20]"
    :background="true"
    layout="total, sizes, prev, pager, next, jumper"
    :total="page.totalCount"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  />

  <el-dialog v-model="dialogFormVisible1" title="种母妊检修改" width="500">
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="ruleForm1"
      label-width="auto"
      :size="formSize"
      status-icon
    >
      <el-form-item el-form-item label="妊检结果" prop="pregnancyTestResult">
        <el-select
          v-model="ruleForm1.pregnancyTestResult"
          placeholder="请选择妊检结果"
        >
          <el-option
            v-for="item in pregntest"
            :label="item.pregnancyTestResultName"
            :value="item.pregnancyTestResult"
          />
        </el-select>
      </el-form-item>
      <el-form-item el-form-item label="妊检方式" prop="pregnancyTestMethod">
        <el-select
          v-model="ruleForm1.pregnancyTestMethod"
          placeholder="妊检方式"
        >
          <el-option
            v-for="item in fieldsDatas"
            :label="item.pregnancyCheckMethodName"
            :value="item.pregnancyCheckMethodId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="同胎数" prop="litterCount">
        <el-input v-model="ruleForm1.litterCount" placeholder="同胎数" />
      </el-form-item>
      <el-form-item label="妊娠天数" prop="pregnancyDays">
        <el-input v-model="ruleForm1.pregnancyDays" placeholder="妊娠天数" />
      </el-form-item>
      <el-form-item label="当前栋舍" prop="currentBarn">
        <el-input v-model="ruleForm1.currentBarn" placeholder="当前栋舍" />
      </el-form-item>
      <el-form-item label="当前栏位" prop="currentPen">
        <el-input v-model="ruleForm1.currentPen" placeholder="当前栏位" />
      </el-form-item>
      <el-form-item label="转入栋舍" prop="transferBarn">
        <el-input v-model="ruleForm1.transferBarn" placeholder="转入栋舍" />
      </el-form-item>
      <el-form-item label="转入栏位" prop="transferPen">
        <el-input v-model="ruleForm1.transferPen" placeholder="转入栏位" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="resetForm(ruleFormRef)"
          >清空</el-button
        >
        <el-button type="primary" @click="dialogFormVisible1 = false"
          >返回</el-button
        >
        <el-button type="primary" @click="submitForm1(ruleFormRef)">
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {
  Check,
  Delete,
  Edit,
  Message,
  Search,
  Star,
  Plus,
} from '@element-plus/icons-vue';
import { reactive, ref, onMounted, computed } from 'vue';
import axios from 'axios';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { ComponentSize, FormInstance, FormRules } from 'element-plus';
//调用持久化
import { useCounterStore } from '@/stores/counter';
const ruleFormRef = ref<FormInstance>();
const counterStore = useCounterStore();
const route = useRoute();
const router = useRouter();
const multipleSelection = ref<any>([]);
const dialogFormVisible = ref(false);
const formSize = ref<ComponentSize>('default');

const handleSelectionChange = (val: any) => {
  multipleSelection.value = val;
  form.motherGivingBirthIds = multipleSelection.value.map(
    (item: any) => item.motherGivingBirthId
  );
  console.log(form.motherGivingBirthIds);
};

const page = reactive({
  pageIndex: 1,
  pageSize: 5,
  totalCount: 0,
  pageCount: 0,
});

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  form.pageSize = val;
  getDatas();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  form.pageIndex = val;
  getDatas();
};

//定义变量
const form = reactive({
  motherGivingBirthIds: [],
  earNo: '',
  leader: '',
  pregnancyTestResult: '',
  litterCount: '',
  DateTime: [],
  pageIndex: 1,
  pageSize: 2,
  totalPage: 1,
  totalCount: 1,
});

//计算属性
const totals = computed(() => {
  let totalNumber = 0;
  form.motherGivingBirthIds.forEach((item: any) => {
    totalNumber += 1;
  });
  return totalNumber;
});

const tableData = ref([]);
const getDatas = () => {
  let minDate = null;
  let maxDate = null;
  if (form.DateTime !== null) {
    minDate = form.DateTime[0];
    maxDate = form.DateTime[1];
  }
  axios
    .post('http://localhost:5039/api/ProductionManagement/Handle1', {
      earNo: form.earNo || 0,
      leader: form.leader,
      pregnancyTestResult: form.pregnancyTestResult || 0,
      litterCount: form.litterCount || 0,
      minDate: minDate,
      maxDate: maxDate,
      pageIndex: page.pageIndex,
      pageSize: page.pageSize,
    })
    .then((res) => {
      console.log(res.data);
      tableData.value = res.data.data.data;
      page.totalCount = res.data.data.totalCount;
      page.pageCount = res.data.data.pageCount;
    });
};

//获取耳号下拉信息
const sleepInfoDatas: any = ref([]);
const getSleepInfos = () => {
  axios.get('http://localhost:5039/api/SleepBegin/SelectEar').then((res) => {
    console.log(res);
    sleepInfoDatas.value = res.data.item;
  });
};

//获取妊检结果下拉信息
const pregntest: any = ref([]);
const getResults = () => {
  axios
    .post('http://localhost:5039/api/ProductionManagement/Handle5')
    .then((res) => {
      console.log(111, res);
      pregntest.value = res.data.data;
    });
};

//种母妊检删除
const handleDelete = (ewePregnancyCheckRecordId: number) => {
  var request: any = ref({});
  request.ids = ewePregnancyCheckRecordId.toString();
  ElMessageBox.confirm('确认删除吗?', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      axios
        .delete('http://localhost:5039/api/ProductionManagement/Handle2', {
          data: request,
          headers: {
            'Content-Type': 'application/problem+json;charset=UTF-8',
          },
        })
        .then((res) => {
          if (res.data.code > 0) {
            ElMessage.success('删除成功');
            getDatas();
          } else {
            ElMessage.error('删除失败，再试试...');
            return;
          }
        });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消操作',
      });
    });
};

//种母妊检修改
const ruleForm1 = reactive({
  ewePregnancyCheckRecordId: '',
  leader: '',
  pregnancyTestDate: '',
  earNo: '',
  pregnancyTestResult: 0,
  pregnancyTestResultName: '',
  pregnancyCheckMethodName: '',
  pregnancyTestMethod: 0,
  litterCount: 0,
  pregnancyDays: 0,
  currentBarn: '',
  currentBarnId:'',
  currentPen:'',
  currentPenId: '',
  transferBarn: '',
  transferBarnId: '',
  transferPen: '',
  transferPenId:'',
  notes: '',
  documentNo: '',
  serialNo: '',
  deletes: false,
  createId: 1,
  createTime: '',
  updateId: 1,
  updateTime: '',
  deleteId: 1,
  deleteTime: '',
  examId: 1,
  examTime: '',
});
//种母妊检反填
const dialogFormVisible1 = ref(false);
const detailCottage = (data: any) => {
  dialogFormVisible1.value = true;
  console.log(data);
  console.log(data.leader);
  // request.ewePregnancyCheckRecordId = ewePregnancyCheckRecordId;
  ruleForm1.ewePregnancyCheckRecordId = data.ewePregnancyCheckRecordId;
  ruleForm1.leader = data.leader;
  ruleForm1.pregnancyTestDate = data.pregnancyTestDate;
  ruleForm1.earNo = data.earNo;
  ruleForm1.pregnancyTestResult = data.pregnancyTestResult;
  ruleForm1.pregnancyTestResultName = data.pregnancyTestResultName;
  (ruleForm1.pregnancyCheckMethodName = data.pregnancyCheckMethodName),
    (ruleForm1.pregnancyTestMethod = data.pregnancyTestMethod),
    (ruleForm1.litterCount = data.litterCount);
  ruleForm1.pregnancyDays = data.pregnancyDays;
  ruleForm1.currentBarn = data.currentBarn;
  ruleForm1.currentBarnId = data.currentBarnId;
  ruleForm1.currentPen = data.currentPen;
  ruleForm1.currentPenId = data.currentPenId;
  ruleForm1.transferBarn = data.transferBarn;
  ruleForm1.transferBarnId = data.transferBarnId;
  ruleForm1.transferPen = data.transferPen;
  ruleForm1.transferPenId = data.transferPenId;
  ruleForm1.notes = data.notes;
  ruleForm1.documentNo = data.documentNo;
  ruleForm1.serialNo = data.serialNo;
  ruleForm1.deletes = data.deletes;
  ruleForm1.createTime = data.createTime;
  ruleForm1.updateTime = data.updateTime;
  ruleForm1.deleteTime = data.deleteTime;
  ruleForm1.examTime = data.examTime;
};

//修改妊检信息
const submitForm1 = async (formEl: FormInstance | undefined) => {
  let data = {
  "ewePregnancyCheckRecordId":ruleForm1.ewePregnancyCheckRecordId,
  "leader": "",
  "pregnancyTestDate": new Date(),
  "earNo": 0,
  "pregnancyTestResult":  ruleForm1.pregnancyTestResult,
  "pregnancyTestMethod": ruleForm1.pregnancyTestMethod,
  "litterCount": ruleForm1.litterCount,
  "pregnancyDays": ruleForm1.pregnancyDays,
  "currentBarn": ruleForm1.currentBarnId,
  "currentPen": ruleForm1.currentPenId,
  "transferBarn": ruleForm1.transferBarnId,
  "transferPen": ruleForm1.transferPenId,
  "notes": 0,
  "documentNo": "",
  "serialNo": "",
  "createId": counterStore.employeeId,
  "createTime":new Date(),
  "updateId": counterStore.employeeId,
  "updateTime": new Date(),
  "deleteId": counterStore.employeeId,
  "deletes": true,
  "deleteTime": null,
  "examId": counterStore.employeeId,
  "examTime": null
  };
  console.log(data);
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      axios
        .put('http://localhost:5039/api/ProductionManagement/Handle4', data)
        .then((res) => {
          if (res.data.code == 0) {
            ElMessage.success('妊检信息修改成功');
            dialogFormVisible1.value = false;
            getDatas();
          } else {
            ElMessage.error('修改妊检失败了，再试试...');
            return;
          }
        });
    } else {
      console.log('error submit!', fields);
    }
  });
};

onMounted(() => {
  getDatas(); //获取数据
  getSleepInfos();
  getResults();
  getMethod();
});

//清空
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

//获取妊检方式
const fieldsDatas: any = ref([]);
const getMethod = () => {
  axios
    .post('http://localhost:5039/api/ProductionManagement/Handle6')
    .then((res) => {
      console.log(res.data.data);
      fieldsDatas.value = res.data.data;
    });
};
</script>

<style scoped>
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}

.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
</style>
